const express = require('express');
const router = express.Router();
const userService = require('../service/user')
const Result = require('../app/Result')
const config = require("../app/config")
var jwt = require('jsonwebtoken')
var expressjwt = require('../app/expressjwt')

const login = async (req, res)=>{
    const user = await userService.queryUser(req.body.username,req.body.password);
    if(user){
        var token = jwt.sign({ username: user.username }, config.secret_key, { algorithm: 'HS256'});
        res.json(Result.ok({token}))
    }else{
        res.json(Result.error({},'账号或者密码错误！'));       
    }
    
}

const queryUsers = async (req,res) => {
    let rows =  await userService.queryUsers();
    res.json(Result.ok(rows))
}

const getUserInfo = async (req,res) =>{
    let username = req.auth.username;
    console.log('username= ' + username);
    const user  = await userService.queryUserInfo(username);
    var data = {
        name: req.auth.username,
        roles:['admin'],
        avatar: user.avatar,
    }
    res.json(Result.ok(data))
}


router.post('/user/login',login)
router.get('/user/list',queryUsers)
router.get('/user/info',expressjwt,getUserInfo)

/* 使用正则表达式来排除连接 */
router.use(expressjwt.unless({path:[/user\/login/,/user\/register/,/public/]}))  
module.exports = router